<template>
  <a-spin :spinning="loading">
    <div class="bg-white">
      <!-- <a-alert showIcon class="mt-10">
        <span slot="message"
          >当一个地点被多个范围覆盖时，展示的费用优先级按照 免费>价格低>价格高的方式采用，到达方式优先级按照
          送车上门>联系接送>自行到店的方式采用。</span
        >
      </a-alert> -->

      <div class="p-10">
        <a-table :columns="columns" class="" :data-source="pageList" :pagination="false">
          <!--名称+颜色-->
          <template #nameColor="val, data">
            <div v-if="data.isEditOrAddTableItem">
              <div class="flex items-center">
                <colorPicker v-model="data.color" class="ss-color" />
                <a-input placeholder="请输入名称" :maxLength="60" v-model="data.name" class="ml-10"></a-input>
              </div>
            </div>
            <div v-else class="flex items-center">
              <div class="ss-color-box w-30 h-15" :style="{ background: data.color }"></div>
              <div class="ml-10">{{ data.name }}</div>
            </div>
          </template>

          <!--开始时间+结束时间-->
          <template #time="val, data">
            <div v-if="data.isEditOrAddTableItem" class="flex items-center">
              <a-time-picker
                :value="moment(data.openingTime, 'HH:mm')"
                format="HH:mm"
                class="mr-10"
                @change="timeChange($event, 'openingTime', data)"
              />
              <a-time-picker
                :value="moment(data.closingTime, 'HH:mm')"
                format="HH:mm"
                @change="timeChange($event, 'closingTime', data)"
              />
            </div>
            <div v-else>
              <span>{{ data.openingTime }}-{{ data.closingTime }}</span>
            </div>
          </template>

          <!--提前预定时间-->
          <template #aheadHour="val, data">
            <div v-if="data.isEditOrAddTableItem">
              <a-input-number :min="1" :max="100000" v-model="data.aheadHour" :precision="0"></a-input-number>
            </div>
            <div v-else>{{ data.aheadHour }}小时</div>
          </template>

          <!--送取车费用 0 代表免费-->
          <template #fee="val, data">
            <div v-if="data.isEditOrAddTableItem">
              <a-input-number :min="0" :max="1000" v-model="data.fee" :precision="0"></a-input-number>
            </div>
            <div v-else>{{ data.fee == 0 ? '免费' : data.fee + '元/次' }}</div>
          </template>

          <!--到达方式-->
          <template #arrivalType="val, data">
            <div v-if="data.isEditOrAddTableItem" class="arriva">
              <a-select class="w-200" v-model="data.arrivalType" placeholder="请选择到达方式">
                <a-select-option :value="item.value" v-for="(item, index) in arrivalTypeList" :key="index">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </div>
            <div v-else class="arriva">
              {{ arrivalTypeList.find((x) => x.value == data.arrivalType).name }}
            </div>
          </template>

          <!--门店-->
          <template #store="val, data">
            <div>
              {{ storeDetailData && storeDetailData.name }}
            </div>
          </template>

          <!--是否启用-->
          <template #isEnabled="val, data">
            <span :class="data.isEnabled ? 'gba2' : ''">{{ data.isEnabled ? '已启用' : '已禁用' }}</span>
          </template>
        </a-table>
      </div>

      <!--地图-->
      <div class="p-10">
        <div id="container" style="height: 700px"></div>
      </div>

      <!--范围弹框s-->
      <addServiceScopePop
        v-if="isShowRangeEdit"
        :center="mapCenter"
        :id="rangeEditObj.id"
        :color="rangeEditObj.color"
        :nameColor="rangeEditObj.nameColor"
        :coordinatesArr="rangeEditObj.coordinatesArr"
        :city="storeDetailData && storeDetailData.cityName"
        :pageList="pageList"
        :isShowDefaultRange="isShowDefaultRange"
        :callBack="rangeCallBack"
      ></addServiceScopePop>
      <!--范围弹框e-->
    </div>
  </a-spin>
</template>

<script>
import { serviceScopeList } from '@/api/store/index'

import moment from 'moment'
import addServiceScopePop from './addServiceScopePop.vue'
import { getStoreDetail } from '@/api/store/index'
let center_icon = require('@/assets/center_icon.png')

export default {
  name: 'serviceScopeItem',
  components: { addServiceScopePop },
  props: {
    storeId2: {
      // 门店id
      type: String,
      default: null,
    },
    pageList: {
      type: Array,
    },
    storyDetail:{
      type:{}
    }
  },
  data() {
    return {
      storeId: undefined, // 门店id
      loading: true, // 页面是否在加载中
      pageList: [], // 列表总数据
      isEditOrAddTable: false, // 是否编辑或者添加表格数据
      arrivalTypeList: [], // 到达方式列表
      editOrAddTableData: {
        // 编辑或者添加的数据
        id: 0,
        name: '', //范围名称
        color: '#1890ff', // 范围颜色
        aheadHour: 1, // 提前预定时间(小时)
        openingTime: '00:00', // 服务开始营业时间 格式 HH:mm 如 08:30
        closingTime: '23:59', // 服务结束营业时间 格式 HH:mm 如 23:30
        fee: 0, // 送取车费用 0代表免费
        arrivalType: undefined, // 到达方式
        isEnabled: true, // 是否启用
      },
      columns: [
        // 表格头部
        { title: '范围名称', scopedSlots: { customRender: 'nameColor' } }, // 组合
        { title: '服务时间', scopedSlots: { customRender: 'time' } }, // 组合
        { title: '提前预定时间', scopedSlots: { customRender: 'aheadHour' } },
        { title: '送取车费用', scopedSlots: { customRender: 'fee' } },
        { title: '到达方式', scopedSlots: { customRender: 'arrivalType' } },
        { title: '是否启用', scopedSlots: { customRender: 'isEnabled' } },
      ],
      map: null, // 地图对象
      polygon: null, // 矢量图形对象
      rangeEditObj: {}, // 范围编辑的obj
      isShowRangeEdit: false, // 是否显示编辑地图的
      storeDetailData: null, // 门店详情数据
      isAdd: false, // 是否在添加
    }
  },
  watch: {
    addedData() {
      this.data = this.addedData
    },
  },
  computed: {
    isAllEditOrAddTableItem() {
      // 是否在编辑或者在添加中
      return this.pageList.some((x) => x.isEditOrAddTableItem)
    },

    mapCenter() {
      console.log(123123)
      console.log(this.storeDetailData)
      // 地图中心（门店中心）
      return this.storeDetailData && [this.storeDetailData.longitude, this.storeDetailData.latitude]
    },
    isShowDefaultRange() {
      // 是否显示默认的圈圈
      return (
        ((this.storeDetailData && this.storeDetailData.openingTime && this.storeDetailData.closingTime) ||
          (this.storeDetailData && this.storeDetailData.isOpenTwentyfourHours)) &&
        this.pageList.some((x) => x.isSystemGenerate)
      )
    },
    storeList() {
      // 门店列表
      return this.$store.getters.storeList
    },
  },

  async created() {
    this.$utils.getDictList('ArrivalType').then((res) => {
      //变速箱类型
      this.arrivalTypeList = res
    })
    // this.storeId = this.storeId2 ? this.storeId2 * 1 : this.storeList[0] && this.storeList[0].id
    this.$store.dispatch('setStoreId', this.storeId)
    // if(this.storeId2!==)
  },

  methods: {
    moment,
    /*地图相关s*/
    iniMap() {
      // 初始化地图
      console.log(this.pageList)
      console.log(this.storeDetailData)
      this.map = new AMap.Map('container', {
        center: this.mapCenter,
        zoom: 12,
      })
      this._polygon() // 初始化地图坐标
      this.isShowDefaultRange && this.creatStoreCircle() // 绘制门店中心
    },
    _polygon() {
      // 初始化矢量地图范围
      this.pageList.map((x1) => {
        x1.coordinatesArr.length > 0 &&
          x1.coordinatesArr.map((x2) => {
            this._addCenterMark(this.$utils.getPointsCenter(x2), x1.color, x1.name) // 设置文案
            this.map.add(
              new AMap.Polygon({
                map: this.map,
                path: x2,
                strokeColor: 'rgba(24,144,255,.01)',
                strokeWeight: 6,
                strokeOpacity: 0.4,
                fillOpacity: 0.6,
                fillColor: x1.color,
                zIndex: 50,
                bubble: true, // 事件冒泡到地图上
              })
            )
          })
      })
    },

    creatStoreCircle() {
      // 绘制圆
      let e = this.pageList.find((x) => x.isSystemGenerate)
      let center = this.mapCenter // 门店中心
      let circle = new AMap.Circle({
        center,
        radius: 5000, //半径
        borderWeight: 3,
        strokeColor: e.color,
        strokeWeight: 6,
        strokeOpacity: 0.1,
        fillOpacity: 0.2,
        strokeStyle: 'solid',
        strokeDasharray: [10, 10],
        // 线样式还支持 'dashed'
        fillColor: '#1791fc',
        zIndex: 0,
        extData: {
          type: 'circle',
        },
      })

      this.map.add(circle)

      let text = new AMap.Text({
        text: e.name,
        anchor: 'center', // 设置文本标记锚点
        style: {
          padding: '5px 5px',
          'background-color': '#188ffd',
          'border-width': '2px',
          'text-align': 'center',
          'font-size': '16px',
          color: '#ffffff',
          'border-color': 'rgba(0,0,0,.1)',
          'border-style': 'solid',
          'max-width': '300px',
          opacity: 1,
        },
        position: center,
        extData: {
          type: 'circle',
        },
      })
      text.setMap(this.map)

      let iconMark = new AMap.Marker({
        position: this.mapCenter,
        anchor: 'center',
        size: new AMap.Size(30, 30),
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
        offset: new AMap.Pixel(5, -30),
      })

      this.map.add(iconMark)
    },

    _addCenterMark(center, backgroundColor, text) {
      // 添加中心覆盖物
      let textMark = new AMap.Text({
        text,
        anchor: 'center', // 设置文本标记锚点
        style: {
          padding: '5px 5px',
          'background-color': backgroundColor,
          'border-width': '2px',
          'text-align': 'center',
          'font-size': '14px',
          color: '#ffffff',
          'border-color': 'rgba(0,0,0,.1)',
          'border-style': 'solid',
          'max-width': '300px',
        },
        position: center,
      })
      textMark.setMap(this.map)
    },

    editRangeHandle(e) {
      // 编辑服务范围
      this.rangeEditObj.id = e.id
      this.rangeEditObj.color = e.color
      this.rangeEditObj.coordinatesArr = e.coordinatesArr
      this.rangeEditObj.nameColor = e.name
      this.isShowRangeEdit = true
    },

    async rangeCallBack(e) {
      // 编辑范围的回调
      if (e === 'ok') {
        await this.getData() // 获取列表数据
        this.iniMap() // 初始化地图
      }
      this.isShowRangeEdit = false
    },

    /*地图相关e*/

    getData(storeId, isLoading = true) {
      // 获取列表

      return new Promise((resolve, reject) => {
        isLoading && (this.loading = true)
        serviceScopeList({
          storeId: storeId, // 门店id
          // isContainDisable: false, // 是否包含禁用的数s据
        })
          .then((res) => {
            res = res.map((x1) => {
              return {
                ...x1,
                coordinatesArr:
                  x1.coordinatesArr.length > 0 &&
                  x1.coordinatesArr.map((x2) => {
                    return x2.map((x3) => {
                      return [x3.lng, x3.lat]
                    })
                  }),
              }
            })
            this.pageList = res
            this.storeDetailData=this.storyDetail
            // this._getStoreDetail(storeId)
            this.$nextTick(() => {
              this.iniMap()
            })
            resolve()
          })
          .finally(() => {
            isLoading && (this.loading = false)
          })
      })
    },

    _getStoreDetail(storeId) {
      // 门店详情
      return new Promise((resolve, reject) => {
        getStoreDetail({
          storeId: storeId, // 门店id
        })
          .then((res) => {
            this.storeDetailData = res
            console.log(this.storeDetailData)
            resolve()
          })
          .finally(() => {
            this.loading = false
          })
      })
    },

    editHandle(e) {
      // 编辑
      if (this.isAllEditOrAddTableItem) return this.$message.error('请先保存/取消当前编辑项')
      this.$set(e, 'isEditOrAddTableItem', true)
    },

    isEnabledHandle(e, d) {
      // 编辑状态
      if (this.isAllEditOrAddTableItem) return this.$message.error('请先保存/取消当前编辑项')
      console.log(e, d)
      this._changeServiceScopeStatus(e, d)
    },

    _changeServiceScopeStatus(e, d) {
      changeServiceScopeStatus({ id: d.id, isEnabled: e }).then(() => {
        this.$message.success('更新成功')
        this.getData()
      })
    },
    timeChange(e, t, d) {
      // 时间编辑
      d[t] = moment(e).format('HH:mm')
      console.log(d[t])
    },

    addTableHandle() {
      // 添加表格数据
      if (this.isAllEditOrAddTableItem) return this.$message.error('请先保存/取消当前编辑项')
      if (!this.isShowDefaultRange) return this.$message.error('请设置营业时间')
      let addData = {
        id: 0,
        name: '', //范围名称
        color: '#1890ff', // 范围颜色
        aheadHour: 1, // 提前预定时间(小时)
        openingTime: '00:00', // 服务开始营业时间 格式 HH:mm 如 08:30
        closingTime: '23:59', // 服务结束营业时间 格式 HH:mm 如 23:30
        fee: 0, // 送取车费用 0代表免费
        arrivalType: undefined, // 到达方式
        isEnabled: true, // 是否启用
      }
      this.pageList.push({
        ...addData,
        isEditOrAddTableItem: true,
      })
    },

    delHandle(e) {
      // 删除服务范围
      if (this.isAllEditOrAddTableItem) return this.$message.error('请先保存/取消当前编辑项')
      this.$confirm({
        title: '提示',
        content: `确定要删除【${e.name}】吗？`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this._deleteServiceScope(e)
        },
      })
    },

    _deleteServiceScope(e) {
      deleteServiceScope({ id: e.id }).then(async () => {
        this.$message.success('删除成功')
        await this.getData()
        this.iniMap()
      })
    },

    async onStoreChange(e) {
      // 门店改变的时候触发
      await this.getData()
      await this._getStoreDetail()
      this.iniMap()
    },

    saveTableHandle(e) {
      // 添加或者编辑服务范围
      let { openingTime, closingTime, isOpenTwentyfourHours } = this.storeDetailData
      if (!e.name) return this.$message.error('请输入范围名称')
      if (!e.openingTime) return this.$message.error('请选择服务开始时间')
      if (!e.closingTime) return this.$message.error('请选择服务结束时间')
      if (e.closingTime < e.openingTime) return this.$message.error('结束时间不能小于开始时间')
      if (!isOpenTwentyfourHours && (e.openingTime < openingTime || e.closingTime > closingTime))
        return this.$message.error('该范围服务时间不在营业时间之内')
      if (!e.arrivalType) return this.$message.error('请选择一个到达方式')
      console.log(e.openingTime < e.closingTime, e.openingTime, e.closingTime, 'e.openingTime')
      e = {
        ...e,
        storeId: this.storeId, // 门店id
      }
      if (e.id == 0) {
        // 新增
        this._createServiceScope(e)
      } else {
        // 编辑
        this._editServiceScope(e)
      }
      this.getData()
    },

    _createServiceScope(e) {
      // 新增范围
      createServiceScope(e).then(async () => {
        this.$message.success('新增成功')
        await this.getData()
        this.iniMap()
      })
    },

    _editServiceScope(e) {
      // 编辑范围
      editServiceScope(e).then(async () => {
        this.$message.success('更新成功')
        await this.getData()
        this.iniMap()
      })
    },

    cancelTableHandle(e) {
      // 取消编辑或者添加服务范围
      e.isEditOrAddTableItem = false
      if (e.id == 0) {
        this.pageList.splice(
          this.pageList.findIndex((x) => x.id == e.id),
          1
        )
      }
      console.log(e)
      this.getData(false)
    },

    toStoreSettingGuideHandle() {
      // 去门店指引
      this.$router.push({ name: 'StoreSettingGuide', query: { storeId: this.storeId } })
    },
  },
}
</script>

<style scoped>
/deep/ .colorBtn {
  width: 30px !important;
  cursor: pointer;
}

/*/deep/ .box {position: absolute!important; z-index: 10000000000000; left: 50% !important; top: 50%; margin-top: -200px!important; }*/
/deep/ .box {
  position: fixed !important;
  z-index: 10000000000000;
  left: 50% !important;
  top: 50%;
  margin-top: -200px !important;
}
.arriva {
  width: 60%;
  height: 30px;
  line-height: 30px;
  text-align: center;
  color: #fff;
  border-radius: 8px;
  background-color: rgba(2, 167, 240, 0.996078431372549);
}
.gba2 {
  color: rgba(2, 167, 240, 0.996078431372549);
}
</style>